package com.gears_software.sxdc.dccx.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.location.AMapLocation;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gears_software.sxdc.dccx.R;
import com.gears_software.sxdc.dccx.application.DCCXApplication;
import com.gears_software.sxdc.dccx.data.finder.ICPOrderFinder;
import com.gears_software.sxdc.dccx.data.finder.RequestUrl;
import com.gears_software.sxdc.dccx.data.finder.util.GearsErrorHandler;
import com.gears_software.sxdc.dccx.data.model.CPOrderDetailModel;
import com.gears_software.sxdc.dccx.data.model.CheckCancelModel;
import com.gears_software.sxdc.dccx.data.model.MyTripPassengerDetailModel;
import com.gears_software.sxdc.dccx.data.model.PositionEntity;
import com.gears_software.sxdc.dccx.data.model.ResultModel;
import com.gears_software.sxdc.dccx.data.model.request.RCheckPassengerCancelModel;
import com.gears_software.sxdc.dccx.data.model.request.RDriverCancelModel;
import com.gears_software.sxdc.dccx.data.model.request.RPassengerArrivedModel;
import com.gears_software.sxdc.dccx.data.model.request.RPassengerCancelModel;
import com.gears_software.sxdc.dccx.data.model.request.RPassengerDealCancel;
import com.gears_software.sxdc.dccx.ui.map.LocationTask;
import com.gears_software.sxdc.dccx.ui.map.OnLocationGetListener;
import com.gears_software.sxdc.dccx.ui.map.RegeocodeTask;
import com.gears_software.sxdc.dccx.ui.util.MaterialDialogProgress;
import com.github.mzule.activityrouter.annotation.Router;
import com.orhanobut.logger.Logger;
import com.sdsmdg.tastytoast.TastyToast;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.TextArrayRes;
import org.androidannotations.rest.spring.annotations.Body;
import org.androidannotations.rest.spring.annotations.RestService;

import java.text.SimpleDateFormat;
import java.util.List;

import qiu.niorgai.StatusBarCompat;

/**
 * Created by chezhenzhen on 2017/8/16.
 */
@EActivity(R.layout.activity_mytrip_passenger)
@Router(value = "passengertrip/:id", isEActivity = true)
public class MyTripPassengerActivity extends AppCompatActivity implements OnLocationGetListener {
    @App
    DCCXApplication app;
    @ViewById
    TextView actionbar_title;
    @ViewById
    TextView back_icon;
    @ViewById
    TextView right_icon;
    @ViewById
    SimpleDraweeView img_avatar;
    @ViewById
    TextView txt_username;
    @ViewById
    TextView txt_vehicleno;
    @ViewById
    TextView txt_car;
    @ViewById
    TextView txt_vehiclecolor;
    @ViewById
    TextView txt_date;
    @ViewById
    TextView txt_start;
    @ViewById
    TextView txt_end;
    @ViewById
    TextView txt_set;
    @ViewById
    TextView txt_money;
    @ViewById
    TextView txt_tel;
    @ViewById
    TextView txt_cancel;
    @ViewById
    TextView txt_triptime_icon;
    @ViewById
    TextView txt_jiantou_icon;
    @ViewById
    TextView txt_yuding_icon;
    @ViewById
    TextView txt_tripstart_icon;
    @ViewById
    TextView txt_arrive;
    @ViewById
    TextView txt_wenhao_icon;
    @ViewById
    TextView txt_cancel_time;
    @ViewById
    TextView txt_cancel_yuanyi;
    @ViewById
    TextView txt_evaluate;
    @ViewById
    TextView txt_passenger_cancel_icon;
    @ViewById
    TextView txt_pay;
    @ViewById
    RelativeLayout re_cancel;
    @ViewById
    RelativeLayout re_arrive;
    @ViewById
    RelativeLayout re_zhifu;
    @ViewById
    RelativeLayout re_complaint;
    @ViewById
    RelativeLayout re_evaluate;
    @ViewById
    RelativeLayout re_refuse;
    @ViewById
    RelativeLayout re_agree;
    @ViewById
    LinearLayout ly_cancel;
    @ViewById
    RelativeLayout re_peichang;
    @ViewById
    RelativeLayout re_bottom;
    @RestService
    ICPOrderFinder orderFinder;
    @Bean
    GearsErrorHandler errorHandler;
    String id;
    MyTripPassengerDetailModel detailModel;
    MaterialDialogProgress progress;
    Context context;

    //地图部分自己封装的定位包
    private LocationTask mLocationTask;
    private RegeocodeTask mRegeocodeTask;
    String address;
    double latitue;
    double longitude;

    @AfterViews
    void created() {
        context = this;
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorActionbar));

        initIconFont();
        orderFinder.setRestErrorHandler(errorHandler);
        id = getIntent().getStringExtra("id");
        mLocationTask = new LocationTask(this);
        progress = new MaterialDialogProgress(this);
        progress.show("正在加载...");
        getDeatil();
        getPassengerDetail();

    }

    void initIconFont() {
        actionbar_title.setText("我的行程");
        back_icon.setVisibility(View.VISIBLE);
        back_icon.setText(R.string.back_icon);
        back_icon.setTypeface(app.iconfont);
        right_icon.setVisibility(View.GONE);
        txt_tel.setTypeface(app.iconfont);
        txt_triptime_icon.setTypeface(app.iconfont);
        txt_jiantou_icon.setTypeface(app.iconfont);
        txt_tripstart_icon.setTypeface(app.iconfont);
        txt_yuding_icon.setTypeface(app.iconfont);
        txt_wenhao_icon.setTypeface(app.iconfont);
        txt_passenger_cancel_icon.setTypeface(app.iconfont);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        id = getIntent().getStringExtra("id");
        progress.show("正在加载...");
        getDeatil();
        getPassengerDetail();
    }


    @Background
    void getDeatil() {
        ResultModel<MyTripPassengerDetailModel> res = orderFinder.getMyTripPassengerDetail(id);
        showResult(res);
    }

    @UiThread
    void showResult(ResultModel<MyTripPassengerDetailModel> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    detailModel = res.getData();
                    Logger.d("detailid:" + detailModel.getId());
                    if (detailModel.getAvatar() != null && !detailModel.getAvatar().equals("")) {
                        Uri uri = Uri.parse(detailModel.getAvatar() + RequestUrl.avatar);
                        img_avatar.setImageURI(uri);
                    }
                    txt_username.setText(detailModel.getDrivername());
                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    txt_date.setText(sf.format(detailModel.getDeparttime()));
                    txt_start.setText(detailModel.getStartpoint());
                    txt_end.setText(detailModel.getEndpoint());
                    txt_set.setText(String.valueOf(detailModel.getPassengernum()));
                    txt_money.setText(String.valueOf(detailModel.getPrice()));
                    txt_car.setText(detailModel.getCarmodel());
                    txt_vehiclecolor.setText(detailModel.getVehiclecolor());
                    txt_vehicleno.setText(detailModel.getVehicleno());

                    if (detailModel.getCancelparty().equals("1") || (detailModel.getCancelparty().equals("2") && detailModel.getAcceptcancel() != null)
                            || detailModel.getCancelparty().equals("3")) {
                        txt_passenger_cancel_icon.setVisibility(View.VISIBLE);
                        re_bottom.setVisibility(View.GONE);
                    } else if (detailModel.getIsconfirm().equals("1")) {
                        txt_passenger_cancel_icon.setVisibility(View.VISIBLE);
                        re_bottom.setVisibility(View.GONE);
                    } else {
                        txt_passenger_cancel_icon.setVisibility(View.GONE);
                        re_bottom.setVisibility(View.VISIBLE);
                        if (detailModel.getDriveraccpet() != null) {
                            re_arrive.setVisibility(View.VISIBLE);
                            re_zhifu.setVisibility(View.VISIBLE);
                            re_evaluate.setVisibility(View.VISIBLE);
                            re_complaint.setVisibility(View.VISIBLE);
                            if (detailModel.getIsoncar() != null && detailModel.getIsoncar().equals("1")) {
                                re_arrive.setEnabled(false);
                                txt_arrive.setTextColor(ContextCompat.getColor(this, R.color.colorFontBigGray));
                            }
                            if (detailModel.getIspay() != null && detailModel.getIspay().equals("1")) {
                                re_zhifu.setEnabled(false);
                                txt_pay.setTextColor(ContextCompat.getColor(this, R.color.colorFontBigGray));
                                txt_pay.setText("已支付");
                                re_evaluate.setVisibility(View.VISIBLE);
                                if (detailModel.getPassengereva() != null && detailModel.getPassengereva().equals("1")) {
                                    txt_evaluate.setText("已评价");
                                    txt_evaluate.setTextColor(ContextCompat.getColor(this, R.color.colorFontBigGray));
                                    re_evaluate.setEnabled(false);
                                } else {
                                    re_evaluate.setEnabled(true);
                                }
                            } else {
                                re_zhifu.setEnabled(true);
                                re_evaluate.setVisibility(View.GONE);
                            }
                        } else {
                            re_arrive.setVisibility(View.GONE);
                            re_zhifu.setVisibility(View.GONE);
                            re_evaluate.setVisibility(View.GONE);
                            re_complaint.setVisibility(View.GONE);
                        }
                    }


                }
            }
        }
        progress.dismiss();
    }

    @Background
    void getPassengerDetail() {
        ResultModel<CPOrderDetailModel> res = orderFinder.getPassengerDetail(id);
        showPassengerDetail(res);
    }

    @UiThread
    void showPassengerDetail(ResultModel<CPOrderDetailModel> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    CPOrderDetailModel orderDetailModel = res.getData();
                    if (orderDetailModel.getCancelparty() != null && orderDetailModel.getCancelparty().equals("2") && orderDetailModel.getCanceldate() != null) {
                        ly_cancel.setVisibility(View.VISIBLE);
                        txt_cancel_yuanyi.setText(orderDetailModel.getCancelreason());
                        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        txt_cancel_time.setText(sf.format(orderDetailModel.getCanceldate()));
                        if (orderDetailModel.getRefusecancel() == null && orderDetailModel.getAcceptcancel() == null) {
                            re_agree.setVisibility(View.VISIBLE);
                            re_refuse.setVisibility(View.VISIBLE);
                        } else {
                            re_agree.setVisibility(View.GONE);
                            re_refuse.setVisibility(View.GONE);
                        }
                    }
                }
            }
        }
    }

    //同意取消
    @Click
    void re_agree() {
        goAgree();
    }

    @Background
    void goAgree() {
        RPassengerDealCancel dealCancel = new RPassengerDealCancel();
        dealCancel.setOrderdetailid(detailModel.getId());
        dealCancel.setType("1");
        ResultModel<String> res = orderFinder.goPassengerDealCancel(dealCancel);
        showAgreeResult(res);
    }

    @UiThread
    void showAgreeResult(ResultModel<String> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                TastyToast.makeText(this, "同意取消成功", app.SHORT, app.SUCCESS);
                txt_passenger_cancel_icon.setVisibility(View.VISIBLE);
                re_agree.setVisibility(View.VISIBLE);
                re_refuse.setVisibility(View.VISIBLE);
            } else {
                TastyToast.makeText(this, "同意取消失败", app.SHORT, app.ERROR);
                txt_passenger_cancel_icon.setVisibility(View.GONE);

                re_agree.setVisibility(View.GONE);
                re_refuse.setVisibility(View.GONE);

            }
        }
    }

    //拒绝取消
    @Click
    void re_refuse() {
        goRefuse();
    }

    @Background
    void goRefuse() {
        RPassengerDealCancel dealCancel = new RPassengerDealCancel();
        dealCancel.setOrderdetailid(detailModel.getId());
        dealCancel.setType("2");
        ResultModel<String> res = orderFinder.goPassengerDealCancel(dealCancel);
        showRefuseResult(res);
    }

    @UiThread
    void showRefuseResult(ResultModel<String> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                re_agree.setVisibility(View.VISIBLE);
                re_refuse.setVisibility(View.VISIBLE);
                TastyToast.makeText(this, "拒绝取消成功", app.SHORT, app.SUCCESS);
            } else {
                TastyToast.makeText(this, "拒绝取消失败", app.SHORT, app.ERROR);
                re_agree.setVisibility(View.GONE);
                re_refuse.setVisibility(View.GONE);

            }
        }
    }

    @Click
    void re_arrive() {
        mLocationTask.setOnLocationGetListener(this);
        mRegeocodeTask = new RegeocodeTask(context);

        //获取定位权限
        AndPermission.with(context)
                .requestCode(200)
                .permission(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                .callback(listener)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(context, rationale).
                                show();
                    }
                })
                .start();


    }

    @Override
    public void onLocationGet(PositionEntity entity, AMapLocation aMapLocation) {
        address = entity.getAddress();
        latitue = entity.getLatitue();
        longitude = entity.getLongitude();
        RPassengerArrivedModel arrivedModel = new RPassengerArrivedModel();
        arrivedModel.setId(detailModel.getId());
        arrivedModel.setOncarlatitude(String.valueOf(latitue));
        arrivedModel.setOncarlongitude(String.valueOf(longitude));
        arrivedModel.setOncarplace(address);
        passengerArrived(arrivedModel);
    }

    @Override
    public void onRegecodeGet(PositionEntity entity) {

    }

    @Background
    void passengerArrived(RPassengerArrivedModel model) {
        ResultModel<String> res = orderFinder.passengerArrived(model);
        showArriveResult(res);
    }

    @UiThread
    void showArriveResult(ResultModel<String> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                TastyToast.makeText(this, "乘客地理位置信息提交成功", app.SHORT, app.SUCCESS);
                re_arrive.setEnabled(false);
                txt_arrive.setTextColor(ContextCompat.getColor(this, R.color.colorFontBigGray));
            } else {
                TastyToast.makeText(this, res.getErrmsg(), app.SHORT, app.ERROR);
            }
        }
    }

    @Click
    void txt_tel() {
        new MaterialDialog.Builder(context)
                .title("提示")
                .titleGravity(GravityEnum.CENTER)
                .titleColorRes(R.color.colorFontBigGray)
                .content("您确定要拨打" + " " + detailModel.getDriverphone())
                .contentColorRes(R.color.colorFontBigGray)
                .positiveText("确定")
                .positiveColor(ContextCompat.getColor(context, R.color.colorFontBlue))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        AndPermission.with(context)
                                .requestCode(100)
                                .permission(Manifest.permission.CALL_PHONE)
                                .callback(listener)
                                .rationale(new RationaleListener() {
                                    @Override
                                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                                        AndPermission.rationaleDialog(context, rationale).
                                                show();
                                    }
                                })
                                .start();
                    }
                })
                .negativeText("取消")
                .negativeColor(ContextCompat.getColor(context, R.color.colorFontGray))
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                })
                .buttonsGravity(GravityEnum.CENTER)
                .show();
    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            // 权限申请成功回调。
            if (requestCode == 100) {
                //打电话
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:" + detailModel.getDriverphone()));
                context.startActivity(intent);
            } else if (requestCode == 200) {
                mLocationTask.startSingleLocate();
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            // 权限申请失败回调。
            if (requestCode == 100) {
                TastyToast.makeText(context, "获取电话权限失败", TastyToast.LENGTH_SHORT, TastyToast.ERROR);
            } else if (requestCode == 200) {
                TastyToast.makeText(context, "获取定位权限失败", TastyToast.LENGTH_SHORT, TastyToast.ERROR);
            }
        }
    };

    @Click
    void re_cancel() {
        RCheckPassengerCancelModel passengerCancelModel = new RCheckPassengerCancelModel();
        passengerCancelModel.setOrderdetailid(detailModel.getId());
        checkPassengerCancel(passengerCancelModel);
    }

    @Background
    void checkPassengerCancel(RCheckPassengerCancelModel passengerCancelModel) {

        ResultModel<CheckCancelModel> res = orderFinder.checkPassengerCancel(passengerCancelModel);
        showCheckPassengerCancelResult(res);
    }

    @UiThread
    void showCheckPassengerCancelResult(ResultModel<CheckCancelModel> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    CheckCancelModel checkCancelModel = res.getData();
                    if (checkCancelModel.getIsok() == 1) {
                        passengerCancel();
                    } else if (checkCancelModel.getIsok() == 2) {
                        new MaterialDialog.Builder(this)
                                .title("提示")
                                .titleGravity(GravityEnum.CENTER)
                                .titleColorRes(R.color.colorFontGray)
                                .content(checkCancelModel.getMsg())
                                .contentColorRes(R.color.colorFontGray)
                                .positiveText("确定")
                                .positiveColor(ContextCompat.getColor(this, R.color.colorFontBlue))
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        passengerCancel();

                                    }
                                })
                                .negativeText("取消")
                                .negativeColor(ContextCompat.getColor(this, R.color.colorFontGray))
                                .onNegative(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                                    }
                                })
                                .buttonsGravity(GravityEnum.CENTER)
                                .show();
                    }
                }
            } else {
                TastyToast.makeText(this, res.getErrmsg(), app.SHORT, app.ERROR);
            }
        }
    }

    private void passengerCancel() {
        new MaterialDialog.Builder(this)
                .title("取消原因")
                .inputRangeRes(2, 30, R.color.colorLine)
                .input(null, null, new MaterialDialog.InputCallback() {
                    @Override
                    public void onInput(MaterialDialog dialog, CharSequence input) {
                        // Do something
                        RPassengerCancelModel cancelModel = new RPassengerCancelModel();
                        cancelModel.setOrderdetailid(detailModel.getId());
                        cancelModel.setReason(input.toString());
                        goPassengerCancel(cancelModel);
                    }
                }).negativeText("取消")
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                }).show();
    }

    @Background
    void goPassengerCancel(RPassengerCancelModel cancelModel) {
        ResultModel<String> res = orderFinder.goPassengerCancel(cancelModel);
        showPassengerCancelResult(res);
    }

    @UiThread
    void showPassengerCancelResult(ResultModel<String> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                txt_passenger_cancel_icon.setVisibility(View.VISIBLE);
                re_bottom.setVisibility(View.GONE);
                TastyToast.makeText(this, "取消行程成功", app.SHORT, app.SUCCESS);
            } else {
                txt_passenger_cancel_icon.setVisibility(View.GONE);
                re_bottom.setVisibility(View.VISIBLE);
                TastyToast.makeText(this, res.getErrmsg(), app.SHORT, app.ERROR);
            }
        }
    }

    @Click
    void re_zhifu() {
        Intent intent = new Intent(this, PayActivity_.class);
        intent.putExtra("type", "4");
        intent.putExtra("orderid", detailModel.getId());
        intent.putExtra("orderNo", detailModel.getOrderid());
        intent.putExtra("driverid", detailModel.getDriverid());
        intent.putExtra("price", detailModel.getPrice());
        intent.putExtra("tradingType", "2");
        startActivityForResult(intent, 5);
    }

    //投诉
    @Click
    void re_complaint() {
        Intent intent = new Intent(this, ComplainActivity_.class);
        intent.putExtra("flag", "2");
        intent.putExtra("id", id);
        intent.putExtra("detailModel", detailModel);
        startActivity(intent);
    }

    //评价
    @Click
    void re_evaluate() {
        Intent intent = new Intent(this, HaveCompletedActivity_.class);
        intent.putExtra("flag", "2");
        intent.putExtra("id", id);
        intent.putExtra("detailModel", detailModel);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            getDeatil();
            getPassengerDetail();
        } else if (requestCode == 5) {
            if (data != null) {
                int code = (int) data.getExtras().get("resultCode");
                if (code == 1) {
                    txt_pay.setText("已支付");
                    txt_pay.setTextColor(ContextCompat.getColor(this, R.color.colorFontBigGray));
                    re_zhifu.setEnabled(false);
                }
            }
        }
    }

    //赔偿说明跳转
    @Click
    void re_peichang() {

    }

    @Click
    void back_icon() {
        this.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationTask.onDestroy();
    }
}
